package com.xwj.nio.udp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * nio通道channel之DatagramChannel
 * UDP协议
 * @author xwj
 * @date 2020/6/10
 */
public class NioUdpServer {
    public static void main(String[] args) throws IOException {
        DatagramChannel dc = DatagramChannel.open();
        dc.configureBlocking(false);
        dc.bind(new InetSocketAddress("127.0.0.1", 9999));
        System.out.println("NioUdpServer启动成功");
        // 开启一个通道选择器
        Selector selector = Selector.open();
        // 将通道注册到选择器
        int key = dc.validOps();;
        dc.register(selector, key);
        // 通过选择器，监听socket连接
        while(selector.select() > 0) {
            // 被选中了的IO事件
            Iterator<SelectionKey> selectionKeyIterator =  selector.selectedKeys().iterator();
            ByteBuffer buf = ByteBuffer.allocate(1024);
            while(selectionKeyIterator.hasNext()) {
                SelectionKey selectionKey = selectionKeyIterator.next();
                // 可读事件，有数据
                if(selectionKey.isReadable()) {
                    SocketAddress socketAddress = dc.receive(buf);
                    buf.flip();
                    System.out.println(new String(buf.array(), 0, buf.limit()));
                    buf.clear();
                }
                selectionKeyIterator.remove();
            }
        }
        selector.close();
        dc.close();
    }
}
